<script setup lang="ts">
import { reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useAuthStore } from '@/state/modules/auth'
import { useUserStore } from '@/state/modules/user'
import { HideLoading, Loading, Toast } from '@/utils/uniapi/prompt'
import { useRouter } from '@/hooks/router'
import { useTmpiniaStore } from '@/tmui/tool/lib/tmpinia'
import tmApp from '@/tmui/components/tm-app/tm-app.vue'
import Iconify from '@/components/Iconify/index.vue'
import { getUserPhoneNumberFromCode } from '@/services/api/weixin/wxOpen'

const store = useTmpiniaStore()

const redirect = ref<string | undefined>(undefined)
onLoad((query) => {
  redirect.value = query?.redirect ? decodeURIComponent(query.redirect) : undefined
})

const router = useRouter()

const form = reactive({
  username: '',
  password: '',
  accept: false,
})
const authStore = useAuthStore()
const userStore = useUserStore()
/** 检测是否接收协议 */
function checkAccept(): Promise<boolean> {
  return new Promise((resolve, reject) => {
    if (form.accept) {
      resolve(true)
      return
    }
    uni.showModal({
      title: '同意并继续',
      content: '请确认以及阅读且同意‘用户服务协议’和‘隐私政策’',
      confirmText: '已阅读',
      success: (e) => {
        if (!e.confirm) {
          console.log('success', false)
          reject(new Error('已取消'))
        }
        else {
          form.accept = true
          resolve(true)
        }
      },
      fail: (res) => {
        reject(res)
      },
    })
  })
}
/** 提交deng */
async function submit() {
  await checkAccept()
  if (!form.username || !form.password) {
    Toast('账号 & 密码 必填', { mask: false })
    return
  }
  if (!form.accept) {
    Toast('请阅读并同意用户隐私政策', { mask: false })
    return
  }
  Loading('login...')
  authStore.login(form)
    .then(async (res) => {
      if (!res || !res.token) {
        Toast('登录失败', { duration: 1500 })
        return
      }
      await userStore.getUserInfoAsync(res.token)
      HideLoading()
      Toast('登录成功', { duration: 1500, icon: 'success' })
      setTimeout(() => {
        if (redirect.value) {
          router.go(redirect.value, { replace: true })
          return
        }
        router.pushTab('/pages/index/my')
      }, 1500)
    })
    .catch(() => HideLoading())
}

/** 微信登录 */
const allowWxLogin = ref(true)
async function wxLogin(e: any) {
  console.log(e) // const { code, errMsg, encryptedData, iv } = e.detail
  const { code, errMsg } = e.detail
  if (!errMsg.includes(':ok'))
    return
  if (!code)
    return
  await checkAccept()
  // code 换取 完整电话号码
  const { error, data: phoneNumber } = await getUserPhoneNumberFromCode(code)
  if (error) {
    Toast(error.msg)
    return
  }
  console.log(phoneNumber)
  Loading('login...')
  authStore.easyLogin(phoneNumber)
    .then(async (res) => {
      if (!res || !res.token) {
        Toast('登录失败', { duration: 1500 })
        return
      }
      await userStore.getUserInfoAsync(res.token)
      HideLoading()
      Toast('登录成功', { duration: 1500, icon: 'success' })
      setTimeout(() => {
        if (redirect.value) {
          router.go(redirect.value, { replace: true })
          return
        }
        router.pushTab('/pages/index/my')
      }, 1500)
    })
    .catch(() => HideLoading())
}

// 切换暗黑模式
const app = ref<InstanceType<typeof tmApp> | null>(null)
function toggleDark() {
  // 切换暗黑模式
  app.value?.setDark()
}
</script>

<template>
  <tm-app ref="app">
    <tm-navbar title="用户登录" :shadow="0" hide-home>
      <template #left>
        <view class="uno-flex uno-items-center uno-gap-10px">
          <tm-text
            :_class="store.tmStore.dark ? 'i-line-md-moon-filled-to-sunny-filled-loop-transition' : 'i-line-md-sunny-filled-loop-to-moon-filled-loop-transition'"
            :color="store.tmStore.dark ? '#FFFB01' : undefined"
            :font-size="18"
            unit="px"
            @click="toggleDark"
          />
        </view>
      </template>
    </tm-navbar>

    <view uno-flex-auto uno-center class="uno-bg-gradient-to-br uno-from-#007dbf:10 uno-via-#009fe8:20 uno-to-#007dbf:10">
      <tm-form id="form" v-model="form" uno-w-75vw _class="uno-flex uno-flex-col uno-gap-y-20px" transprent :margin="[0]" :padding="[32]" @submit="submit">
        <view uno-center uno-flex-col>
          <tm-image src="/static/svg/favicon.svg" :width="80" :height="80" unit="px" uno-mb-10px />
          <tm-text label="LOGIN" :font-size="24" unit="px" uno-font-bold />
          <tm-text label="用户登录" :font-size="12" unit="px" uno-opacity-40 />
        </view>

        <view>
          <tm-input
            v-model="form.username"
            placeholder="请输入用户名" prefix="tmicon-user-fill"
            focus-color="primary" linear="right"
            :margin="[0, 20]" :round="15" :border="10"
          />
          <tm-input
            v-model="form.password"
            password placeholder="请输入密码" prefix="tmicon-lock-fill"
            focus-color="primary" linear="right"
            :margin="[0, 20]" :round="15" :border="10"
          />
          <view uno-flex="~ row" uno-justify-end>
            <navigator url="/pages/user/forget-password" open-type="navigate" uno-flex="~ row" uno-justify-end>
              <tm-text label="忘记密码？" :color="store.tmStore.color || 'primary'" />
            </navigator>
          </view>
        </view>

        <tm-button label="登录" icon="tmicon-unlock" :round="15" block form-type="submit" />

        <view uno-flex="~ row" uno-items-center>
          <tm-checkbox v-model="form.accept" label="我已经阅读并同意" :size="36" :font-size="24" />
          <tm-text label="《用户隐私政策》" :font-size="24" :color="store.tmStore.color || 'primary'" />
        </view>

        <!-- #ifdef MP-WEIXIN -->
        <view v-if="allowWxLogin" uno-flex="~ row" uno-justify-center uno-gap-10px uno-items-center>
          <tm-button :width="120" unit="px" font-color="#55b01c" transprent open-type="getPhoneNumber" @getphonenumber="wxLogin">
            <iconify icon="i-uiw-weixin" />
            <tm-text label="微信登录" uno-ml-10px />
          </tm-button>
        </view>
        <!-- #endif -->
      </tm-form>
    </view>
  </tm-app>
</template>

<style lang="scss" scoped></style>
